package com.szgr.baoyin.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.CommonImagePagerAdapter;
import com.szgr.baoyin.adapter.StoreDetailListAdapter;
import com.szgr.baoyin.model.CartProduct;
import com.szgr.baoyin.model.DetailConfig;
import com.szgr.baoyin.model.GoodsDetail;
import com.szgr.baoyin.model.HomePageImage;
import com.szgr.baoyin.model.OrderGoods;
import com.szgr.baoyin.model.OrderMember;
import com.szgr.baoyin.myview.NoScrollListView;
import com.szgr.baoyin.myview.WheelView;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.RLog;
import com.szgr.baoyin.utils.ToastUtils;
import com.szgr.baoyin.utils.ViewFindUtils;
import com.szgr.baoyin.video.FullScreenVideoActivity;
import com.szgr.baoyin.video.MediaPlayerControl;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 商品详情
 */
public class StoreDeatilActivity extends BaseActivity implements MediaPlayerControl, MediaPlayer.OnCompletionListener, MediaPlayer.OnInfoListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, TextWatcher, Animation.AnimationListener {

    private static final int SHOW_PROGRESS = 2;
    private static final int FADE_OUT = 1;
    private static final int HAS_ADDRESS = 304;
    private static final int NO_ADDRESS = 305;
    private static final int SAVE_SUCCESS = 306;
    private static final int SAVE_FAIL = 307;
    private SurfaceView mSurfaceView;
    private View mController;
    private TextView mTitle;
    private Button btnSize;
    private SeekBar mSeekBar;
    private TextView mCurrTime;
    private TextView mSumTime;
//    private Button mPauseBtn;
    private View loadView;
    private ProgressBar mProgressbar;
    private TextView mBufferPercent;
    private Button mRetryBtn;
    private SurfaceHolder mSurfaceHolder;
    /**
     * 记录当前播放的位置
     */
    private int mPlayPosition = -1;
    /**
     * 播放视频
     */
    private MediaPlayer mPlayer;
    //视频路径
    private String path;
    /**
     * 当前缓存进度
     */
    private int mCurrentBufferPercentage;
    /**
     * mediaController是否显示
     */
    private boolean mShowing;
    private int sDefaultTimeout = 3000;
    private EditText tv_number;
    private int productNumber = 1;
    private Animation cartAnim;
    private ImageView animCar;
    private TextView btn_add;
    private String goods_id;
    private TextView tv_name;
    private TextView tv_price;
    private TextView tv_marketPrice;
    private TextView tv_person;
    private TextView tv_count;
    private TextView tv_setting;
    private Context mContext;
    private GoodsDetail goodsDetail;
    private List<HomePageImage> imgUrls;
    private ViewPager detailPager;
    private CommonImagePagerAdapter pagerAdapter;
    private TextView tv_imageCount;
    private ImageView img_save;
    private UMSocialService controller;
    private HashMap<String, Object> hashMap;
    private ArrayList<OrderGoods> mData;
    private String type;
    private LinearLayout menuView;
    private Dialog menuDialog;
    private int index = 1;
    private WheelView wheelView;
    private TextView tv_dao;
    private TextView tv_xieji;
    private TextView tv_oil;
    private TextView tv_zhou;
    private TextView tv_other;
    private List<DetailConfig> configs;
    private StoreDetailListAdapter detailListAdapter;
    private DetailConfig detailConfig;
    private View chooseContainer;
    private TextView tv_baseName;
    private TextView tv_allMoney;
    private ScrollView detailScrollView;
    private WebView productWebView;
    private TextView tv_adv1;
    private TextView tv_adv2;
    private boolean isChooseAccessory = false;
    private WebView settingWebView;
    private LinearLayout innerLinear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_store_deatil);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("商品详情");
        actionBarRight.setImageResource(R.drawable.car);
        actionBarRight.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(MyApplication.getmInstance().getCartNum() > 0){
            actionBarCount.setVisibility(View.VISIBLE);
            actionBarCount.setText(MyApplication.getmInstance().getCartNum() + "");
        }else{
            actionBarCount.setVisibility(View.GONE);
        }
    }

    @Override
    public void initView() {
//        RelativeLayout rl_top = (RelativeLayout) findViewById(R.id.store_detail_top_image);
//        ViewGroup.LayoutParams params = rl_top.getLayoutParams();
//        params.height = MyTool.getScreenWidth(getWindowManager());
//        rl_top.setLayoutParams(params);
        detailScrollView = (ScrollView) findViewById(R.id.detail_scroll_view);
        innerLinear = ViewFindUtils.find(view,R.id.inner);

        mContext = this;
        Intent intent = getIntent();
        if(intent != null && intent.hasExtra("type")){
            type = intent.getStringExtra("type");
        }

        View videoView = findViewById(R.id.store_detail_video_view);
        videoView.setOnClickListener(this);
        findViewById(R.id.store_detail_choose_color_category).setOnClickListener(this);
//        path = "http://img1.peiyinxiu.com/2014121211339c64b7fb09742e2c.mp4";
//        initVideo();
        imgUrls = new ArrayList<>();
        detailPager = (ViewPager) findViewById(R.id.store_detail_pager);
        pagerAdapter = new CommonImagePagerAdapter(mContext, imgUrls,true);
        detailPager.setAdapter(pagerAdapter);
        tv_imageCount = (TextView) findViewById(R.id.store_detail_image_count);
        detailPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tv_imageCount.setText((position + 1) + "/" + imgUrls.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        img_save = (ImageView) findViewById(R.id.store_detail_save_goods);
        img_save.setOnClickListener(this);
        ImageView img_share = (ImageView) findViewById(R.id.store_detail_share_goods);
        img_share.setOnClickListener(this);

//        ImageLoader.ImageListener listener = ImageLoader.getImageListener(topImage,R.drawable.loading,R.drawable.loading);
//        MyApplication.getmInstance().getImageLoader().get(mGoods.getGoods_image(), listener);

        tv_name = (TextView) findViewById(R.id.store_detail_goods_name);
        tv_setting = (TextView) findViewById(R.id.store_detail_setting);
        tv_price = (TextView) findViewById(R.id.store_detail_new_price);
        tv_marketPrice = (TextView) findViewById(R.id.store_detail_old_price);
        tv_person = (TextView) findViewById(R.id.store_detail_person);
        tv_count = (TextView) findViewById(R.id.store_detail_count);
        tv_adv1 = (TextView) findViewById(R.id.store_item_place);
        tv_adv2 = (TextView) findViewById(R.id.fuk_android);
        findViewById(R.id.product_canshu).setOnClickListener(this);
        findViewById(R.id.product_setting).setOnClickListener(this);
        productWebView = (WebView)findViewById(R.id.product_web_view);
        settingWebView = (WebView)findViewById(R.id.product_web_view_setting);
        WebSettings settings1 = settingWebView.getSettings();
        settings1.setJavaScriptEnabled(true);
        settingWebView.loadUrl(Constant.URL_SETTING);
        WebSettings settings = productWebView.getSettings();
//        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);

        findViewById(R.id.store_detail_minus).setOnClickListener(this);
        findViewById(R.id.store_detail_add).setOnClickListener(this);
        tv_number = (EditText) findViewById(R.id.store_detail_number);
        tv_number.addTextChangedListener(this);

        animCar = (ImageView) findViewById(R.id.store_detail_car);
        cartAnim = AnimationUtils.loadAnimation(this, R.anim.cart_anim);
        cartAnim.setAnimationListener(this);

        btn_add = (TextView) findViewById(R.id.store_detail_add_car);
        btn_add.setOnClickListener(this);

        findViewById(R.id.store_detail_submit_order).setOnClickListener(this);
        findViewById(R.id.store_detail_link_server).setOnClickListener(this);
        if(intent.hasExtra("goods_id")){
            goods_id = intent.getStringExtra("goods_id");
            getGoodsDetail(goods_id);
        }
        initUMENG();

        judgeIsSaved(goods_id);

//        tv_dao = (TextView) findViewById(R.id.detail_choose_dao);
//        tv_dao.setOnClickListener(this);
//        tv_xieji = (TextView) findViewById(R.id.detail_choose_xieji);
//        tv_xieji.setOnClickListener(this);
//        tv_oil = (TextView) findViewById(R.id.detail_choose_oil);
//        tv_oil.setOnClickListener(this);
//        tv_zhou = (TextView) findViewById(R.id.detail_choose_zhou);
//        tv_zhou.setOnClickListener(this);
//        tv_other = (TextView) findViewById(R.id.detail_choose_other);
//        tv_other.setOnClickListener(this);

        tv_baseName = (TextView) findViewById(R.id.goods_base_name);
        tv_allMoney = (TextView) findViewById(R.id.detail_all_money);
        chooseContainer = findViewById(R.id.detail_container_00);
//        View daoContainer = findViewById(R.id.detail_container_01);
//        View jiContainer = findViewById(R.id.detail_container_02);
//        View oilContainer = findViewById(R.id.detail_container_03);
//        View zhouContainer = findViewById(R.id.detail_container_04);
//        View otherContainer = findViewById(R.id.detail_container_05);

        configs = new ArrayList<>();
        NoScrollListView nslv_detail = (NoScrollListView) findViewById(R.id.detail_config);
        detailListAdapter = new StoreDetailListAdapter(this, configs ,this);
        nslv_detail.setAdapter(detailListAdapter);
    }

    private void judgeIsSaved(final String goods_id) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_IS_SAVE, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("------>" + s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if(jsonObject.has("datas")){
                        JSONObject datas = jsonObject.getJSONObject("datas");
                        if(datas.has("result")){
                            String result = datas.getString("result");
                            if("0".equals(result)){
                                mHandler.obtainMessage(SAVE_SUCCESS).sendToTarget();
                            }else if("1".equals(result)){
                                mHandler.obtainMessage(SAVE_FAIL).sendToTarget();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("fav_type","goods");
                map.put("fav_id",goods_id);
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void initUMENG() {

        String appId = "wxe929555b52e418e9";
        String appSecret = "d4624c36b6795d1d99dcf0547af5443d";
// 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(this,appId,appSecret);
        wxHandler.addToSocialSDK();

// 添加微信朋友圈
        UMWXHandler wxCircleHandler = new UMWXHandler(this,appId,appSecret);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();

        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "1104943894","Mqwv9iqSbTtwAwH7");
        qZoneSsoHandler.addToSocialSDK();

        //参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, "1104943894",
                "Mqwv9iqSbTtwAwH7");
        qqSsoHandler.addToSocialSDK();


    }

    /**
     * 获取商品详情
     */
    private void getGoodsDetail(final String goods_id) {
        DialogUtils.showLoadingDialog(this,"正在拼命加载中...");
        StringRequest jor = new StringRequest(Request.Method.GET, Constant.URL_GOODS_DETAIL_1 + "&goods_id=" + goods_id,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String str) {
                        System.out.println("---detail--->" + goods_id + str);
                        System.out.println("---key--->" + MyApplication.getmInstance().getKey());
                        try {
                            JSONObject jsonObject = new JSONObject(str);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            if(datas.has("error")){
                                String error = datas.getString("error");
                                ToastUtils.showToast(error);
                            }else if(datas.has("goods_info")){
                                JSONObject goods_info = datas.getJSONObject("goods_info");
                                Gson gson = new Gson();
                                GoodsDetail goodsDetail = gson.fromJson(goods_info.toString(), GoodsDetail.class);

                                if(datas.has("goods_image")){
                                    String goods_image = datas.getString("goods_image");
                                    String[] goods_image_mobile = goods_image.split(",");
                                    for (int i = 0; i < goods_image_mobile.length; i++) {
                                        HomePageImage hpi = new HomePageImage();
                                        hpi.setImage(goods_image_mobile[i]);
                                        imgUrls.add(hpi);
                                    }
                                    pagerAdapter.notifyDataSetChanged();
                                }

                                if(datas.has("accessories_array")){

                                    JSONObject accessories_array = datas.getJSONObject("accessories_array");
                                    Iterator<String> keys1 = accessories_array.keys();
                                    if(keys1.hasNext()){
                                        JSONObject jsonObject11 = accessories_array.getJSONObject(keys1.next());
                                        if(jsonObject11.has("goods_list")) {
                                            JSONObject goods_list = jsonObject11.getJSONObject("goods_list");
                                            Iterator<String> keys = goods_list.keys();
                                            while (keys.hasNext()) {
                                                String name = keys.next();
                                                JSONArray dao = goods_list.getJSONArray(name);
                                                Gson gson1 = new Gson();
                                                List<DetailConfig.DetailConfigItem> list = gson1.fromJson(dao.toString(), new TypeToken<List<DetailConfig.DetailConfigItem>>() {
                                                }.getType());
                                                DetailConfig detailConfig = new DetailConfig();
                                                detailConfig.setName(name);
//                                        detailConfig.setCheckedItem(list.get(0));
                                                detailConfig.setData(list);
                                                detailConfig.setPrice("0");
                                                configs.add(detailConfig);
                                            }
                                        }else{
                                            mHandler.obtainMessage(860).sendToTarget();
                                        }
                                    }

//                                    if(goods_list.has("刀库")){
//                                        JSONArray dao = goods_list.getJSONArray("刀库");
//                                        Gson gson1 = new Gson();
//                                        List<DetailConfig.DetailConfigItem> list = gson1.fromJson(dao.toString(),new TypeToken<List<DetailConfig.DetailConfigItem>>(){}.getType());
//                                        DetailConfig detailConfig = new DetailConfig();
//                                        detailConfig.setName("刀库");
////                                        detailConfig.setCheckedItem(list.get(0));
//                                        detailConfig.setData(list);
//                                        detailConfig.setPrice("0");
//                                        configs.add(detailConfig);
//                                    }
//                                    if(goods_list.has("屑机")){
//                                        JSONArray dao = goods_list.getJSONArray("屑机");
//                                        Gson gson1 = new Gson();
//                                        List<DetailConfig.DetailConfigItem> list = gson1.fromJson(dao.toString(),new TypeToken<List<DetailConfig.DetailConfigItem>>(){}.getType());
//                                        DetailConfig detailConfig = new DetailConfig();
//                                        detailConfig.setName("排屑机");
////                                        detailConfig.setCheckedItem(list.get(0));
//                                        detailConfig.setData(list);
//                                        detailConfig.setPrice("0");
//                                        configs.add(detailConfig);
//                                    }
//                                    if(goods_list.has("油冷机")){
//                                        JSONArray dao = goods_list.getJSONArray("油冷机");
//                                        Gson gson1 = new Gson();
//                                        List<DetailConfig.DetailConfigItem> list = gson1.fromJson(dao.toString(),new TypeToken<List<DetailConfig.DetailConfigItem>>(){}.getType());
//                                        DetailConfig detailConfig = new DetailConfig();
//                                        detailConfig.setName("油冷机");
////                                        detailConfig.setCheckedItem(list.get(0));
//                                        detailConfig.setData(list);
//                                        detailConfig.setPrice("0");
//                                        configs.add(detailConfig);
//                                    }
//                                    if(goods_list.has("四轴")){
//                                        JSONArray dao = goods_list.getJSONArray("四轴");
//                                        Gson gson1 = new Gson();
//                                        List<DetailConfig.DetailConfigItem> list = gson1.fromJson(dao.toString(),new TypeToken<List<DetailConfig.DetailConfigItem>>(){}.getType());
//                                        DetailConfig detailConfig = new DetailConfig();
//                                        detailConfig.setName("四轴");
////                                        detailConfig.setCheckedItem(list.get(0));
//                                        detailConfig.setData(list);
//                                        detailConfig.setPrice("0");
//                                        configs.add(detailConfig);
//                                    }
//                                    if(goods_list.has("其他")){
//                                        JSONArray dao = goods_list.getJSONArray("其他");
//                                        Gson gson1 = new Gson();
//                                        List<DetailConfig.DetailConfigItem> list = gson1.fromJson(dao.toString(),new TypeToken<List<DetailConfig.DetailConfigItem>>(){}.getType());
//                                        DetailConfig detailConfig = new DetailConfig();
//                                        detailConfig.setName("其他");
////                                        detailConfig.setCheckedItem(list.get(0));
//                                        detailConfig.setData(list);
//                                        detailConfig.setPrice("0");
//                                        configs.add(detailConfig);
//                                    }
                                }
                                if(configs.size() == 0){
                                    mHandler.obtainMessage(860).sendToTarget();
                                }else {
                                    detailListAdapter.setConfigs(configs);
                                }

                                mHandler.obtainMessage(850,goodsDetail).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        MyApplication.getmInstance().addToRequestQueue(jor);
    }

    /**
     * 初始化视频界面
     */
    private void initVideo() {
        mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        mSurfaceView.setOnClickListener(this);
        mController = findViewById(R.id.ll_controller);
        // mController.setOnClickListener(this);

        mTitle = (TextView) findViewById(R.id.tv_title);
        btnSize = (Button) findViewById(R.id.btn_change_size);

        mSeekBar = (SeekBar) findViewById(R.id.seekBar);
        mSeekBar.setMax(1000);
        mCurrTime = (TextView) findViewById(R.id.tv_curr_time);
        mSumTime = (TextView) findViewById(R.id.tv_sum_time);

        findViewById(R.id.btn_back).setOnClickListener(this);
        // 暂停/播放
        // mPauseBtn = (ImageButton) findViewById(R.id.btn_pause);
//        mPauseBtn = (Button) findViewById(R.id.btn_pause);
//        mPauseBtn.setOnClickListener(this);

        loadView = findViewById(R.id.ll_buffer);
        mProgressbar = (ProgressBar) findViewById(R.id.progressBar);
//        showLoadingProgressbar(true);
        mBufferPercent = (TextView) findViewById(R.id.tv_buffer_percent);

        mRetryBtn = (Button) findViewById(R.id.btn_retry);
        mRetryBtn.setOnClickListener(this);

        mSurfaceView.getHolder().addCallback(mSHCallback);
        mSurfaceView.getHolder().setType(
                SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mSurfaceView.setFocusable(true);
        mSurfaceView.setFocusableInTouchMode(true);
        mSurfaceView.requestFocus();
    }

    SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback() {
        public void surfaceChanged(SurfaceHolder holder, int format, int w,
                                   int h) {
            // if (mSeekWhenPrepared != 0)
            // {
            // seekTo(mSeekWhenPrepared);
            // }
            if (mPlayPosition != 0) {
                seekTo(mPlayPosition);
            }

            start();
        }

        public void surfaceCreated(SurfaceHolder holder) {
            mSurfaceHolder = holder;
            openVideo();
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // after we return from this we can't use the surface any more
            mSurfaceHolder = null;
            hide();
            release();
        }
    };

    private Handler mHandler = new Handler() {
        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        public void handleMessage(Message msg) {
            Log.i("fcy", "------------- handler.msg.what=" + msg.what);
            int pos;
            switch (msg.what) {
                case FADE_OUT: // 隐藏
                    hide();
                    break;
                case SHOW_PROGRESS: // 更新进度条
                    pos = setProgress(); // 当前播放位置（毫秒数）
                    if (mShowing && mPlayer.isPlaying()) { // 在handleMessage中再次发送消息（延迟发送，形成每隔x发送一次）
                        msg = obtainMessage(SHOW_PROGRESS);
                        // fixme 为什么不是1000
                        sendMessageDelayed(msg, 1000 - (pos % 1000));
                    }
                    break;
                case Constant.REQUEST_SUCCESS:
                    getCart();
                    break;
                case 850:
                    //获取详情成功
                    DialogUtils.hideLoadingDialog();
                    goodsDetail = (GoodsDetail) msg.obj;

                    productWebView.loadData(goodsDetail.getGoods_body(), "text/html", "utf-8");

                    if(",9,".equals(goodsDetail.getGoods_stcids())){
                        type = Constant.TYPE_01;
                    }else if(",12,".equals(goodsDetail.getGoods_stcids())){
                        type = Constant.TYPE_03;
                    }

                    //TODO
//                    if(Constant.TYPE_03.equals(type)) {
//                        btn_add.setOnClickListener(StoreDeatilActivity.this);
//                    }else{
//                        btn_add.setVisibility(View.GONE);
//                    }

                    if(Constant.TYPE_03.equals(type)){
                        chooseContainer.setVisibility(View.GONE);
//            daoContainer.setVisibility(View.GONE);
//            jiContainer.setVisibility(View.GONE);
//            oilContainer.setVisibility(View.GONE);
//            zhouContainer.setVisibility(View.GONE);
//            otherContainer.setVisibility(View.GONE);
                    }

                    String goods_name = goodsDetail.getGoods_name();
                    if(Constant.TYPE_03.equals(type)){
                        tv_baseName.setText(goods_name);
                    }else{
                        String[] split = goods_name.split(" ");
                        tv_baseName.setText(split[0]);
                    }
                    tv_name.setText(goods_name);
                    String goods_jingle = goodsDetail.getGoods_jingle();
                    if(goods_jingle != null && goods_jingle.contains("；")){
                        String replace = goods_jingle.replace("；", System.lineSeparator());
                        tv_setting.setText(replace);
                    }else {
                        tv_setting.setText(goods_jingle);
                    }
                    tv_price.setText("¥" + goodsDetail.getGoods_price() + "元");
                    tv_marketPrice.setText("市场价" + goodsDetail.getGoods_marketprice() + "元");
                    tv_person.setText(goodsDetail.getGoods_salenum() + "人付款");
                    tv_count.setText("库存：" + goodsDetail.getGoods_storage() + "件");
                    tv_imageCount.setText((detailPager.getCurrentItem() + 1) + "/" + imgUrls.size());
                    tv_adv1.setText(goodsDetail.getGoods_jingle2());
                    tv_adv2.setText(goodsDetail.getGoods_jingle3());
                    caculatePrice();
                    break;
                case 860://获取配置的列表是空的
                    DialogUtils.hideLoadingDialog();
                    chooseContainer.setVisibility(View.GONE);
                    break;
                case 333:
                    //收藏商品成功
                    ToastUtils.showToast("收藏商品成功");
                    img_save.setImageResource(R.drawable.save_04);
                    break;
                case 33:
                    //TODO 如果没请求到数据，如何处理？
                    break;
                case 34:
                    MyApplication.getmInstance().setCartNum((int) msg.obj);
                    if(animCar.getVisibility() == View.GONE) {
                        animCar.setVisibility(View.VISIBLE);
                    }
                    animCar.startAnimation(cartAnim);
                    break;
                case HAS_ADDRESS:
                    HashMap<String,String> map = (HashMap<String, String>) msg.obj;
                    Intent hasIntent = new Intent(StoreDeatilActivity.this, MyOrderDetailActivity.class);
                    hasIntent.putExtra("address_map", map);
                    hasIntent.putExtra("mData",mData);
                    hasIntent.putExtra("hashMap",hashMap);
                    hasIntent.putExtra("isZero","0");//是否来自购物车
                    hasIntent.putExtra("type",type);
                    startActivity(hasIntent);
                    break;
                case NO_ADDRESS:
                    Intent noIntent = new Intent(StoreDeatilActivity.this, MyOrderDetailActivity.class);
                    noIntent.putExtra("mData",mData);
                    noIntent.putExtra("hashMap",hashMap);
                    noIntent.putExtra("isZero","0");//是否来自购物车
                    noIntent.putExtra("type", type);
                    startActivity(noIntent);
                    break;
                case SAVE_SUCCESS:
                    img_save.setImageResource(R.drawable.save_03);
                    break;
                case SAVE_FAIL:
                    img_save.setImageResource(R.drawable.save_04);
                    break;
            }
        }
    };

    /**
     * 购物车
     */
    private void getCart() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_GET_CART,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---get cart-->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            if("200".equals(code) && jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                if(datas.has("cart_list")){
                                    JSONArray cart_list = datas.getJSONArray("cart_list");
                                    Gson gson = new Gson();
                                    List<CartProduct> list = gson.fromJson(cart_list.toString(),new TypeToken<List<CartProduct>>(){}.getType());
                                    if(list.size() == 0){
                                        mHandler.obtainMessage(33).sendToTarget();
                                    }else{
                                        mHandler.obtainMessage(34,list.size()).sendToTarget();
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    /**
     * 设置播放进度条、缓冲进度、视频总时长，当前播放位置
     *
     * @return 当前播放的位置（milliseconds）
     */
    private int setProgress() {
        int position = mPlayer.getCurrentPosition();
        int duration = mPlayer.getDuration();
        if(position == duration){
            seekTo(0);
        }
        if (mSeekBar != null) {
            if (duration > 0) {
                // use long to avoid overflow
                long pos = 1000L * position / duration;
                mSeekBar.setProgress((int) pos);
            }
            int percent = getBufferPercentage();
            mSeekBar.setSecondaryProgress(percent * 10);
        }

        if (mSumTime != null) // fixme 每次都设置好么？放到prepare完成后，设置一下就好了
            mSumTime.setText(getShowTime(duration));
        if (mCurrTime != null)
            mCurrTime.setText(getShowTime(position));

        return position;
    }

    /**
     * 转换播放时间
     *
     * @param milliseconds 传入毫秒值
     * @return 返回 hh:mm:ss或mm:ss格式的数据
     */
    @SuppressLint("SimpleDateFormat")
    public String getShowTime(long milliseconds) {
        // 获取日历函数
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        SimpleDateFormat dateFormat = null;
        // 判断是否大于60分钟，如果大于就显示小时。设置日期格式
        if (milliseconds / 60000 > 60) {
            dateFormat = new SimpleDateFormat("hh:mm:ss");
        } else {
            dateFormat = new SimpleDateFormat("mm:ss");
        }
        return dateFormat.format(calendar.getTime());
    }

    /**
     * Remove the controller from the screen.
     */
    public void hide() {
        // if (mAnchor == null)
        // return;

        if (mShowing) {
            try { // 隐藏的时候，将消息移除，不再处理该消息（进度条不再走，只有显示的时候才处理进度条）
                mHandler.removeMessages(SHOW_PROGRESS);
                // 隐藏controller
                // mWindowManager.removeView(mDecor);

                if (mController != null) {
                    mController.setVisibility(View.GONE);
                }
            } catch (IllegalArgumentException ex) {
                Log.w("MediaController", "already removed");
            }
            mShowing = false;
        }
    }

    /*
     * release the media player in any state
	 */
    private void release() {
        if (mPlayer != null) {
            mPlayer.reset();
            mPlayer.release();
            mPlayer = null;
        }
    }

    /**
     * 播放视频
     */
    public void openVideo() {
        release(); // release(false)
        // 初始化MediaPlayer
        mPlayer = new MediaPlayer();
        // 重置mediaPalyer,建议在初始化mediaplay立即调用。
        // mPlayer.reset();
        // 设置声音效果
        // mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        // 设置播放完成监听
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnInfoListener(this);
        // 设置媒体加载完成以后回调函数，可以播放了
        mPlayer.setOnPreparedListener(this);
        // 错误监听回调函数
        mPlayer.setOnErrorListener(this);
        // 设置缓存变化监听
        mPlayer.setOnBufferingUpdateListener(this);
        mCurrentBufferPercentage = 0;
        // 传递url
        if (TextUtils.isEmpty(path)) {
            Toast.makeText(this, "加载视频错误！", Toast.LENGTH_LONG).show();
            return;
        }
        // fixme 这里也可能异常，建议放到try里，cath exception
        Uri uri = Uri.parse(path);
        try {
            mPlayer.setDataSource(this, uri);
            // 设置异步加载视频，包括两种方式 prepare()同步，prepareAsync()异步
            // mPlayer.prepare();

            mPlayer.setDisplay(mSurfaceHolder);
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setScreenOnWhilePlaying(true);
            mPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "加载视频错误！", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 是否要显示
     *
     * @param isShow
     */
    public void showLoadingProgressbar(boolean isShow) {
        if (mProgressbar == null)
            return;

        if (isShow) { // 需要显示
            mProgressbar.setVisibility(View.VISIBLE);
//            mPauseBtn.setVisibility(View.GONE);
        } else {
            mProgressbar.setVisibility(View.GONE);
//            mPauseBtn.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.action_bar_right:
                if(MyApplication.getmInstance().isLogin()) {
                    startActivity(new Intent(this, CartActivity.class));
                }else {
                    startActivity(new Intent(this,LoginActivity.class));
                }
                break;
//            case R.id.store_detail_video_view:
//                Intent videoView = new Intent(this, FullScreenVideoActivity.class);
//                startActivity(videoView);
//                break;
            case R.id.store_detail_choose_color_category:
//                Intent chooseIntent = new Intent(this,ChooseSettingActivity.class);
//                startActivity(chooseIntent);
                break;
            case R.id.surfaceView:
                if(isPlaying()) {
                    toggleMediaControlsVisibility();
                }
                break;
            case R.id.btn_back:
                Intent videoView = new Intent(this, FullScreenVideoActivity.class);
                startActivity(videoView);
                break;
            case R.id.store_detail_minus:
                if(productNumber > 1){
                    productNumber -- ;
                    tv_number.setText(productNumber + "");
                    caculatePrice();
                }
                break;
            case R.id.store_detail_add:
                productNumber ++;
                tv_number.setText(productNumber + "");
                caculatePrice();
                break;
            case R.id.store_detail_add_car:
                if(MyApplication.getmInstance().isLogin()) {
                    addToCart(goods_id);
                }else {
                    startActivity(new Intent(this,LoginActivity.class));
                }
                break;
            case R.id.store_detail_submit_order:
                if(MyApplication.getmInstance().isLogin()) {
//                    if(Constant.TYPE_01.equals(type)){
                        for (int i = 0; i < configs.size(); i++) {
                            DetailConfig.DetailConfigItem checkedItem = configs.get(i).getCheckedItem();
                            if (checkedItem != null && !"不选".equals(checkedItem.getName())) {
                                isChooseAccessory = true;
                            }
                        }
//                    }

                    if(!isChooseAccessory) {
                        submitOrder();
                    }else{
                        addToCart(goods_id);
                        for (int i = 0; i < configs.size(); i++) {
                            DetailConfig.DetailConfigItem checkedItem = configs.get(i).getCheckedItem();
                            if (checkedItem != null && !"不选".equals(checkedItem.getName())) {
                                addToCart(checkedItem.getId());
                            }
                        }
                    }

                }else {
                    startActivity(new Intent(this,LoginActivity.class));
                }

//                startActivity(new Intent(this,MyOrderDetailActivity.class));
                break;
            case R.id.store_detail_link_server:
                Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + Constant.PHONE));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case R.id.store_detail_save_goods:

                if(MyApplication.getmInstance().isLogin()) {
                    saveGoods("add");
                }else {
                    startActivity(new Intent(this,LoginActivity.class));
                }
                break;
            case R.id.store_detail_share_goods:

                if(MyApplication.getmInstance().isLogin()) {
                    if(imgUrls != null && imgUrls.size() > 0){
                        String imgUrl = imgUrls.get(0).getImage();
                        shareGoods(goodsDetail.getGoods_name(),imgUrl);
                        controller.openShare(this, false);
                    }
                }else {
                    startActivity(new Intent(this,LoginActivity.class));
                }
                break;
//            case R.id.detail_choose_dao:
//                List<String> daos = new ArrayList<>();
//                daos.add("123");
//                daos.add("456");
//                daos.add("789");
//                initDialog("刀库",1);
//                wheelView.setItems(daos);
//                menuDialog.show();
//                break;
//            case R.id.detail_choose_xieji:
//                List<String> xiejis = new ArrayList<>();
//                xiejis.add("987");
//                xiejis.add("654");
//                xiejis.add("321");
//                initDialog("排屑机",2);
//                wheelView.setItems(xiejis);
//                menuDialog.show();
//                break;
//            case R.id.detail_choose_oil:
//                List<String> oils = new ArrayList<>();
//                oils.add("qwe");
//                oils.add("rty");
//                oils.add("uio");
//                initDialog("油冷机",3);
//                wheelView.setItems(oils);
//                menuDialog.show();
//                break;
//            case R.id.detail_choose_zhou:
//                List<String> zhous = new ArrayList<>();
//                zhous.add("asd");
//                zhous.add("fgh");
//                zhous.add("jkl");
//                initDialog("四轴",4);
//                wheelView.setItems(zhous);
//                menuDialog.show();
//                break;
//            case R.id.detail_choose_other:
//                List<String> others = new ArrayList<>();
//                others.add("asd");
//                others.add("fgh");
//                others.add("jkl");
//                initDialog("其他",5);
//                wheelView.setItems(others);
//                menuDialog.show();
//                break;
            case R.id.config_choose_01:
            case R.id.config_choose:
                int tag = (int) v.getTag();
                detailConfig = configs.get(tag);
                List<DetailConfig.DetailConfigItem> data = detailConfig.getData();
                initDialog(detailConfig.getName(), tag);
                List<String> strs = new ArrayList<>();
                strs.add("不选");
                for (DetailConfig.DetailConfigItem dci : data) {
                    strs.add(dci.getName());
                }
                wheelView.setItems(strs);
                menuDialog.show();
                break;
            case R.id.product_canshu:
                if(goodsDetail != null) {
                    if(Constant.TYPE_01.equals(type)) {
                        if(productWebView.getVisibility() == View.GONE) {
                            productWebView.setVisibility(View.VISIBLE);

                            RLog.s("---h--->" + detailScrollView.getScrollY() + MyTool.getScreenHeight(getWindowManager()));
                            scrollToBottom(detailScrollView,innerLinear,productWebView);
                        }else{
                            productWebView.setVisibility(View.GONE);
                        }
                    }
                }
                break;
            case R.id.product_setting:
                if(goodsDetail != null) {
                    if(Constant.TYPE_01.equals(type)) {
                        if(settingWebView.getVisibility() == View.GONE) {
                            settingWebView.setVisibility(View.VISIBLE);
//                            WebSettings settings = settingWebView.getSettings();
//                            settings.setJavaScriptEnabled(true);
//                            settingWebView.loadUrl(Constant.URL_SETTING);
                            scrollToBottom(detailScrollView,innerLinear,settingWebView);
                        }else{
                            settingWebView.setVisibility(View.GONE);
                        }
                    }
                }
                break;
        }
    }

    public static void scrollToBottom(final View scroll,final View inner,final View view){
        Handler mHandler = new Handler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if(scroll == null || inner == null){
                    return ;
                }

                scroll.scrollTo(0,view.getTop());
            }
        });
    }

    /**
     * 计算总价格
     */
    private void caculatePrice() {
        if(goodsDetail != null) {
            double all = 0;
            for (int i = 0; i < configs.size(); i++) {
                DetailConfig.DetailConfigItem checkedItem = configs.get(i).getCheckedItem();
                if (checkedItem != null) {
                    all += Double.parseDouble(checkedItem.getPrice());
                }
            }

            all = (all + Double.parseDouble(goodsDetail.getGoods_price())) * productNumber;
            tv_allMoney.setText(MyTool.formatDouble(all) + "");
        }
    }

    public void initDialog(String title, final int position){
        menuView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.layout_wheel_view,null);
        View confirm = menuView.findViewById(R.id.confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(index == 1) {
                    DetailConfig.DetailConfigItem detailConfigItem = new DetailConfig().getItem();
                    detailConfigItem.setName("不选");
                    detailConfigItem.setPrice("0");
                    detailConfig.setCheckedItem(detailConfigItem);
                    detailListAdapter.notifyDataSetChanged();

                }else{
                    List<DetailConfig.DetailConfigItem> data = detailConfig.getData();
                    DetailConfig.DetailConfigItem detailConfigItem = data.get(index - 2);
                    detailConfig.setCheckedItem(detailConfigItem);
                    detailListAdapter.notifyDataSetChanged();
                }

                menuDialog.dismiss();
                index = 1;
                caculatePrice();
            }
        });
        View cancel = menuView.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuDialog.dismiss();
                index = 1;
            }
        });
        TextView tv_title = (TextView) menuView.findViewById(R.id.title);
        tv_title.setText(title);
        wheelView = (WheelView) menuView.findViewById(R.id.wheel_view);

        wheelView.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                index = selectedIndex;
            }
        });
        menuDialog = MyTool.getMenuDialog(this, menuView);
    }

    /**
     * 提交订单
     */
    private void submitOrder() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_SUBMIT_ORDER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("------>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.has("datas")) {
                                JSONObject datas = jsonObject.optJSONObject("datas");
                                if (datas.has("vat_hash")) {
                                    String vat_hash = datas.optString("vat_hash");
                                    String freight_hash = datas.optString("freight_hash");
                                    JSONObject offpay = datas.optJSONObject("offpay");


                                    hashMap = new HashMap<>();
                                    hashMap.put("vat_hash", vat_hash);
                                    hashMap.put("freight_hash", freight_hash);

                                    JSONObject store_cart_list = datas.optJSONObject("store_cart_list");
                                    JSONObject six = store_cart_list.optJSONObject("6");
                                    JSONArray goods_list = six.optJSONArray("goods_list");
                                    Gson gson = new Gson();
                                    mData = gson.fromJson(goods_list.toString(), new TypeToken<List<OrderGoods>>() {
                                    }.getType());

                                    JSONObject jsonObject1 = datas.optJSONObject("store_points_list");
                                    Iterator<String> keys = jsonObject1.keys();
                                    while(keys.hasNext()){
                                        JSONObject jsonObject2 = jsonObject1.getJSONObject(keys.next());
                                        OrderMember orderMember = gson.fromJson(jsonObject2.toString(), OrderMember.class);
                                        hashMap.put("orderMember",orderMember);
                                    }

                                    Object address_info = datas.get("address_info");
                                    if (address_info instanceof JSONObject) {
                                        if(offpay != null) {
                                            String offpay_hash = offpay.optString("offpay_hash");
                                            hashMap.put("offpay_hash", offpay_hash);
                                            //TODO 有地址信息
                                            JSONObject addJson = (JSONObject) address_info;
                                            HashMap<String, String> map = new HashMap<>();
                                            map.put("address_id", addJson.getString("address_id"));// "430",
                                            map.put("member_id", addJson.getString("member_id"));// "835",
                                            map.put("true_name", addJson.getString("true_name"));// "\u4efb\u91d1\u9e4f",
                                            map.put("area_id", addJson.getString("area_id"));// "37",
                                            map.put("city_id", addJson.getString("city_id"));// "36",
                                            map.put("area_info", addJson.getString("area_info"));// "\u5317\u4eac\u5317\u4eac\u5e02\u4e1c\u57ce\u533a",
                                            map.put("address", addJson.getString("address"));// "\u4fdd\u94f6\u673a\u5e8a",
                                            map.put("tel_phone", addJson.getString("tel_phone"));// "",
                                            map.put("mob_phone", addJson.getString("mob_phone"));// "18501967780",
                                            map.put("is_default", addJson.getString("is_default"));// "0"

                                            mHandler.obtainMessage(HAS_ADDRESS, map).sendToTarget();
                                        }else{
                                            mHandler.obtainMessage(NO_ADDRESS).sendToTarget();
                                        }

                                    } else if (address_info instanceof JSONArray) {
                                        //TODO 没有地址信息
                                        mHandler.obtainMessage(NO_ADDRESS).sendToTarget();
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                StringBuffer sb = new StringBuffer();
                sb.append(goodsDetail.getGoods_id() + "|" + productNumber + ",");
//                for (int i = 0; i < configs.size(); i++) {
//                    DetailConfig.DetailConfigItem checkedItem = configs.get(i).getCheckedItem();
//                    if(checkedItem != null){
//                        if(i == configs.size() -1){
//                            sb.append(checkedItem.getId() + "|1");
//                        }else{
//                            sb.append(checkedItem.getId() + "|1" + ",");
//                        }
//                    }
//
//                }
                map.put("cart_id",sb.toString());
                map.put("ifcart", "0");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    /**
     * 分享
     */
    private void shareGoods(String content,String imgUrl) {
        // 首先在您的Activity中添加如下成员变量
        controller = UMServiceFactory.getUMSocialService("com.umeng.share");
// 设置分享内容
        controller.setShareContent(content);
// 设置分享图片, 参数2为图片的url地址

        controller.setShareMedia(new UMImage(this, imgUrl));

        QQShareContent qqShareContent = new QQShareContent();
//设置分享文字
        qqShareContent.setShareContent("售价" + goodsDetail.getGoods_price() + "元");
//设置分享title
        qqShareContent.setTitle(goodsDetail.getGoods_name());
//设置分享图片
        qqShareContent.setShareImage(new UMImage(this, imgUrl));
//设置点击分享内容的跳转链接
        qqShareContent.setTargetUrl("http://123.57.75.202/baoyin/shop/index.php");
        controller.setShareMedia(qqShareContent);

        //微信
        //设置微信好友分享内容
        WeiXinShareContent weixinContent = new WeiXinShareContent();
//设置分享文字
        weixinContent.setShareContent("售价" + goodsDetail.getGoods_price() + "元");
//设置title
        weixinContent.setTitle(goodsDetail.getGoods_name());
//设置分享内容跳转URL
        weixinContent.setTargetUrl("http://123.57.75.202/baoyin/shop/index.php");
//设置分享图片
        weixinContent.setShareImage(new UMImage(this,imgUrl));
        controller.setShareMedia(weixinContent);

        //设置微信朋友圈分享内容
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent("售价" + goodsDetail.getGoods_price() + "元");
//设置朋友圈title
        circleMedia.setTitle(goodsDetail.getGoods_name());
        circleMedia.setShareImage(new UMImage(this,imgUrl));
        circleMedia.setTargetUrl("http://123.57.75.202/baoyin/shop/index.php");
        controller.setShareMedia(circleMedia);

        //设置新浪SSO handler
        controller.getConfig().setSsoHandler(new SinaSsoHandler());

//        controller.getConfig().setSsoHandler(new SinaSsoHandler());
// 设置分享图片，参数2为本地图片的资源引用
//mController.setShareMedia(new UMImage(getActivity(), R.drawable.icon));
// 设置分享图片，参数2为本地图片的路径(绝对路径)
//mController.setShareMedia(new UMImage(getActivity(),
//                                BitmapFactory.decodeFile("/mnt/sdcard/icon.png")));

// 设置分享音乐
//UMusic uMusic = new UMusic("http://sns.whalecloud.com/test_music.mp3");
//uMusic.setAuthor("GuGu");
//uMusic.setTitle("天籁之音");
// 设置音乐缩略图
//uMusic.setThumb("http://www.umeng.com/images/pic/banner_module_social.png");
//mController.setShareMedia(uMusic);

// 设置分享视频
//UMVideo umVideo = new UMVideo(
//          "http://v.youku.com/v_show/id_XNTE5ODAwMDM2.html?f=19001023");
// 设置视频缩略图
//umVideo.setThumb("http://www.umeng.com/images/pic/banner_module_social.png");
//umVideo.setTitle("友盟社会化分享!");
//mController.setShareMedia(umVideo);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = controller.getConfig().getSsoHandler(requestCode) ;
        if(ssoHandler != null){
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    /**
     * 收藏商品
     */
    private void saveGoods(final String action) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_SAVE_GOODS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("------>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if(jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                if(datas.has("result")){
                                    String result = datas.getString("result");
                                    if("1".equals(result)){
                                        mHandler.obtainMessage(333).sendToTarget();
                                    }
                                }else if(datas.has("error")){
                                    String error = datas.getString("error");
                                    ToastUtils.showToast(error);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtils.showToast("收藏失败");
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("goods_id",goods_id);
                map.put("act",action);
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    /**
     * 加入购物车
     */
    private void addToCart(final String newGoodsId) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_ADD_TO_CART,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("------>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            if("200".equals(code) && jsonObject.has("datas")){
                                Object datas = jsonObject.get("datas");
                                if(datas instanceof String){
                                    mHandler.obtainMessage(Constant.REQUEST_SUCCESS).sendToTarget();
                                }else if(datas instanceof JSONObject){
                                    JSONObject json = (JSONObject) datas;
                                    String error = json.getString("error");
                                    ToastUtils.showToast(error);
                                }
                            }
                        } catch (JSONException e) {
                            ToastUtils.showToast("添加失败");
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtils.showToast("添加失败");
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("goods_id",newGoodsId);
                map.put("quantity",productNumber + "");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void toggleMediaControlsVisibility() {
        if (isShowing()) {
            hide();
        } else {
            show();
        }
    }

    public boolean isShowing() {
        return mShowing;
    }

    /********************************************MediaPlayerControl****************************************************/
    @Override
    public void start() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.start();
        }
    }

    @Override
    public void pause() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.pause();
        }
    }

    @Override
    public int getDuration() {
        return mPlayer.getDuration();
    }

    @Override
    public int getCurrentPosition() {
        return mPlayer.getCurrentPosition();
    }

    @Override
    public void seekTo(int pos) {
        mPlayer.seekTo(pos);
    }

    @Override
    public boolean isPlaying() {
        return mPlayer.isPlaying();
    }

    @Override
    public int getBufferPercentage() {
        if (mPlayer != null) {
            return mCurrentBufferPercentage;
        }
        return 0;
    }
    /************************************************************************************************/

    @Override
    public void onCompletion(MediaPlayer mp) {
        hide();
    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START: {
                updateLoadState(false);
                return true;
            }
            case MediaPlayer.MEDIA_INFO_BUFFERING_START: { // 卡顿的时候，让controller一直显示，知道开始播放才消失
                updateLoadState(true);
                return true;
            }
            case MediaPlayer.MEDIA_INFO_BUFFERING_END: {
                updateLoadState(false);
                return true;
            }
        }
        return false;
    }

    /**
     * 更新loading状态
     *
     * @param isLoading
     */
    public void updateLoadState(boolean isLoading) {
        if (isLoading) {// 正在加载
            show(0);
            showLoadingProgressbar(true);
        } else {
            hide();
            showLoadingProgressbar(false);
        }
    }

    /**
     * TODO Show the controller on screen. It will go away automatically after
     * 'timeout' milliseconds of inactivity.
     *
     * @param timeout The timeout in milliseconds. Use 0 to show the controller
     *                until hide() is called.
     */
    public void show(int timeout) {
        if (!mShowing) {
            setProgress();
//            if (mPauseBtn != null) {
//                mPauseBtn.requestFocus();
//            }
            // 显示 MediaController
            // mWindowManager.addView(mDecor, mDecorLayoutParams);
            mController.setVisibility(View.VISIBLE);
            mShowing = true;
        }
        updatePausePlay(0);

        // cause the progress bar to be updated even if mShowing
        // was already true. This happens, for example, if we're
        // paused with the progress bar showing the user hits play.
        mHandler.sendEmptyMessage(SHOW_PROGRESS);
        Message msg = mHandler.obtainMessage(FADE_OUT);

        // fixme 系统方法：但是如果调用了show(3000)3s内又调用show(0),那么同样会被隐藏
        // if (timeout != 0)
        // { // 如果是0，那么将消失的msg移除，且不发送, 即会一直显示
        // mHandler.removeMessages(FADE_OUT);
        // mHandler.sendMessageDelayed(msg, timeout);
        // }

        if (timeout != 0) { // 如果是0，那么将消失的msg移除，且不发送, 即会一直显示
            mHandler.removeMessages(FADE_OUT);
            mHandler.sendMessageDelayed(msg, timeout);
        } else { // 修改系统方法
//			Message message = mHandler.obtainMessage(FADE_OUT);
//			if (message != null)
//			{
            mHandler.removeMessages(FADE_OUT);
//			}
        }

    }

    /**
     * 更新暂停图标（暂停、播放、重试）
     */
    private void updatePausePlay(int state) {
        if (mPlayer.isPlaying()) {
            // mPauseBtn.setImageResource(com.android.internal.R.drawable.ic_media_pause);
//            mPauseBtn.setText("暂停");
        } else {
            // mPauseBtn.setImageResource(com.android.internal.R.drawable.ic_media_play);
//            mPauseBtn.setText("播放");
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        // 当视频加载完毕以后，为什么会立刻隐藏加载进度条，哪里掉了hide（如果想加载完毕后，等2s再隐藏，那么）
        // 为什么使用下面两行，依然会立刻隐藏，如果不调用show只调用第二行，那么就不会hide了
        // show(5000);
        showLoadingProgressbar(false);
//		updateLoadState(false); // 包含了hide方法

        // 判断是否有保存的播放位置,防止屏幕旋转时，界面被重新构建，播放位置丢失。
        if (mPlayPosition > 0) {
            mPlayer.seekTo(mPlayPosition);
        }

//		if (mSumTime != null)
//			mSumTime.setText(getShowTime(mPlayer.getDuration()));

        // 设置拖动监听事件
        mSeekBar.setOnSeekBarChangeListener(new SeekBarChangeListener());
        // 视频大小
        btnSize.setOnClickListener(this);
        // TODO 播放视频
        mPlayer.start();
        // 设置显示到屏幕
        // mPlayer.setDisplay(mSurfaceHolder);
//		show(5000);
        show();
        // TODO 设置surfaceView保持在屏幕上
        // mPlayer.setScreenOnWhilePlaying(true);
        // mSurfaceHolder.setKeepScreenOn(true);

    }

    /**
     * Show the controller on screen. It will go away automatically after 3
     * seconds of inactivity.
     */
    public void show() {
        show(sDefaultTimeout);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                ToastUtils.showToast("MEDIA_ERROR_UNKNOWN");
                break;
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                ToastUtils.showToast("MEDIA_ERROR_SERVER_DIED");
                break;
            default:
                break;
        }

        switch (extra) {
            case MediaPlayer.MEDIA_ERROR_IO:
                ToastUtils.showToast("MEDIA_ERROR_IO");
                break;
            case MediaPlayer.MEDIA_ERROR_MALFORMED:
                ToastUtils.showToast("MEDIA_ERROR_MALFORMED");
                break;
            case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                ToastUtils.showToast("MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK");
                break;
            case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                ToastUtils.showToast("MEDIA_ERROR_TIMED_OUT");
                break;
            case MediaPlayer.MEDIA_ERROR_UNSUPPORTED: // 不支持
                ToastUtils.showToast("MEDIA_ERROR_UNSUPPORTED");
                break;
        }
        return false;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        mCurrentBufferPercentage = percent;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.length() >= 1) {
            productNumber = Integer.parseInt(s.toString());
        }else{
            tv_number.setText("1");
            productNumber = 1;
        }
        caculatePrice();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /*****************************anim Listener*************************************/
    @Override
    public void onAnimationStart(Animation animation) {
//        animCar.setVisibility(View.VISIBLE);
        btn_add.setEnabled(false);
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        animCar.setVisibility(View.GONE);
        btn_add.setEnabled(true);
        actionBarCount.setVisibility(View.VISIBLE);
        actionBarCount.setText(MyApplication.getmInstance().getCartNum() + "");
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }
    /******************************************************************/

    /**
     * 进度条 状态改变监听
     */
    private class SeekBarChangeListener implements
            SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            if (!fromUser) {
                return;
            }

            long duration = mPlayer.getDuration();
            long newPosition = (duration * progress) / 1000L;
            mPlayer.seekTo((int) newPosition);
            if (mCurrTime != null)
                mCurrTime.setText(getShowTime((int) newPosition));

            mPlayer.start();
            // 无任何操作后2s后消失，需要调用show(),否则按上次调用show()算后2s消失
            show();
        }

        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        public void onStopTrackingTouch(SeekBar seekBar) {
        }

    }
}
